package com.zhentao.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;

import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.nio.charset.StandardCharsets;

/**
 * 数据库初始化器
 * 用于自动创建表结构和测试数据
 */
@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        try {
            // 读取SQL脚本
            ClassPathResource resource = new ClassPathResource("sql/init_database.sql");
            String sql = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
            
            // 分割SQL语句并执行
            String[] statements = sql.split(";");
            for (String statement : statements) {
                statement = statement.trim();
                if (!statement.isEmpty() && !statement.startsWith("--") && !statement.startsWith("/*")) {
                    try {
                        jdbcTemplate.execute(statement);
                    } catch (Exception e) {
                        // 忽略已存在的表错误
                        if (!e.getMessage().contains("already exists")) {
                            System.out.println("执行SQL失败: " + statement);
                            System.out.println("错误: " + e.getMessage());
                        }
                    }
                }
            }
            System.out.println("数据库初始化完成！");
        } catch (Exception e) {
            System.out.println("数据库初始化失败: " + e.getMessage());
        }
    }
} 



